package at.spengergasse.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.NDC;

/**
 * This filter ensures that the username of the current user is present in the
 * lg4j NDC for the duration of the entire HTTP request, allowing it to be
 * output in logfiles (using the %x parameter)
 * 
 * @author Klaus.Unger $Id: LoggingFilter.java,v 1.1 2010-05-21 13:12:57 leonharj Exp $
 */
public class LoggingFilter implements Filter {
  protected final Log log = LogFactory.getLog(getClass());

  private static final String DEFAULT_USER_PARAM = "defaultUserName";
  private String defaultUserName;

  public void init(FilterConfig cfg) throws ServletException {
    defaultUserName = cfg.getInitParameter(DEFAULT_USER_PARAM);
    log.debug("Default user name: " + defaultUserName);
  }

  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
    // HttpServletRequest request = (HttpServletRequest) req;
    // HttpSession session = request.getSession();
    // String userName = Authentication.getPrincipal()
    String userName = null;
    log.debug("userName set to " + userName);

    if (userName == null) userName = defaultUserName;
    NDC.push(userName);

    try {
      chain.doFilter(req, res);
    }
    finally {
      NDC.pop();
    }
  }

  public void destroy() {
    // left empty intentionally
  }
}
